package dryworks.jsf.examples.generator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class GeneratorFileUtils {
	public static File getFolder(File parent, String name) {
		File result = new File(parent, name);
		if (!result.exists()) {
			result.mkdir();
		}
		return result;
	}

	public static void setFileContent(File folder, String fileName,
			String content, boolean ovewriteExisting) throws IOException {
		File file = new File(folder, fileName);
		if (!file.exists()) {
			file.createNewFile();
		} else {
			if (!ovewriteExisting) {
				return;
			}
		}
		setFileContent(file, content, true);
	}

	public static void setFileContent(File file, String content,
			boolean ovewriteExisting) throws IOException {
		if (!file.exists()) {
			file.createNewFile();
		} else {
			if (!ovewriteExisting) {
				return;
			}
		}

		try {
			FileOutputStream fout = new FileOutputStream(file);
			fout.write(content.getBytes());
			fout.flush();
			fout.close();
		} catch (Exception e) {
			System.err
					.println("cant set file content:" + file + " reason:" + e);
		}
	}

	public static String getFileContent(InputStream in) {

		try {
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(in));
			StringBuffer res = new StringBuffer();
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				res.append(line).append("\n");
			}
			return res.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "no source";
	}

}
